package edu.mit.media.fv.components
{
	import flash.display.MovieClip;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.utils.Timer;
	
	public class AQPlayer extends MovieClip
	{
		private var length:int = 1*60*1000;
		private var duration:int = 0;
		private var timer:Timer;
		
		var _playIcon:DisplayObject;
		var _playStop:DisplayObject;
		var _bar:DisplayObject;
		var _label:TextField;
		
		public function AQPlayer()
		{
			super();
			this.timer = new Timer(1000,0);
			this.timer.addEventListener(TimerEvent.TIMER, onTimer);
			this.timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
		}
		public function processPlayClicked(event:MouseEvent):void{
			this.duration = 0;
			this.removeChild(this._playIcon);
			this.addChild(this._playStop);
			this.dispatchEvent(new AQRecorderEvent(AQRecorderEvent.START_PLAY));
			this.timer.start();
			this._label.text = "Playing";
		}
		public function processPlayStopClicked(event:MouseEvent):void{
			this.removeChild(this._playStop);
			this.addChild(this._playIcon);
			this.dispatchEvent(new AQRecorderEvent(AQRecorderEvent.STOP_PLAY));
			this.timer.stop();
			this.timer.reset();
			this._label.text = "Stopped";
		}
		/**
		 * Sets the length of this recording in numbers of milliseconds.
		 */
		public function setLength(length:int):void{
			if(length <= 0){
				this.length = 1*60*1000;
			}else{
				this.length = length;
			}
		}
		public function onTimer(event:TimerEvent):void{
			this.duration = this.duration+1000;
			
			if(this.duration >=this.length){
				this.removeChild(this._playStop);
				this.addChild(this._playIcon);
				this.dispatchEvent(new AQRecorderEvent(AQRecorderEvent.STOP_PLAY));
				this.timer.stop();
				this.timer.reset();
				this._label.text = "Stopped";
			}else{
				//move tick mark
				this._bar.scaleX = Number(this.duration/this.length);
				this._label.text = getTime(duration)+" / "+getTime(length);
			}
		}
		public function onTimerComplete(event:Timer):void{
			this._bar.scaleX = 1.00;
			this._label.text = getTime(length)+" / "+getTime(length);
		}
		/**
		 * Converts milliseconds into hour:minute.
		 */		
		private function getTime(time:int):String{
			var i:int = time/1000;
			if(i%60 < 10){
				return int(i/60)+":0"+(i%60);
			}else{
				return int(i/60)+":"+(i%60);
			}
			
		}
	}
}